import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  //一级路由(登录和首页)
  //重定向，默认打开的是首页
  { path: '/', redirect: '/home' },
  //组件可以这样的动态导入，当使用到这个标签后，才会调用这个组件
  { path: '/login', component: () => import('@/components/MyLogin') },
  {
    path: '/home',
    component: () => import('@/components/MyHome'),
    // 首页的二级路由
    children: [
      // { path: 'users', component: 用户 },
      // { path: 'rights', component: 权限 },
      // { path: 'orders', component: 订单 },
      // { path: 'goods', component: 商品1 },
      // { path: 'settings', component: 设置 }
      { path: 'users', component: () => import('@/components/menus/MyUsers') },
      { path: 'rights', component: () => import('@/components/menus/MyRights') },
      { path: 'orders', component: () => import('@/components/menus/MyOrders') },
      { path: 'goods', component: () => import('@/components/menus/MyGoods') },
      { path: 'settings', component: () => import('@/components/menus/MySettings') },
      //点击查看用户详情
      { path: 'detail/:id', component: () => import('@/components/user/MyUserDetail') }
    ]
  }
]

const router = new VueRouter({
  routes
})

//全局前置导航守卫
router.beforeEach((to, from, next) => {
  //to 到哪里去  to.path 表示即将要访问的那个地址
  //from 从哪里来
  //next() --表示放行允许通过  next(false) --表示不允许通过
  //next('/login') -- 表示强制跳转到/login中
  if (to.path === '/login') {
    next()//如果访问的是登录页，允许直接放行
  } else {
    if (localStorage.getItem('token')) {
      next()//如果已经登录了（token不为空）
    } else {
      next('/login')//如果没有登录，跳转回登录页面
    }
  }
})
export default router
